package teamblue.cardex.activities;


import java.text.DateFormat;
import java.text.DecimalFormat;
import java.util.Calendar;

import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;

import teamblue.cardex.R;
import teamblue.cardex.components.Card;
import teamblue.cardex.components.CardexDb;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.AdapterView.OnItemSelectedListener;

public class AddEditCard extends Activity {

	private final static int MISSING_NAME_DIALOG = 0;
	private final static int EXPIRE_DATE_DIALOG = 1;
	private final static int BARCODE_DIALOG = 2;
	private CardexDb mDb;
	private Card mCard;
	private Button date_button;
	private Button save;
	private TextView expire;
	private EditText number;
	final static DecimalFormat my_format = new DecimalFormat("#,##0.00");
	final DecimalFormat my_format2 = new DecimalFormat("###0.00");
	

	final static int ADD_CARD = 3;
	final static int SAVE_CARD = 4;
	final static int CANCEL = 5;
	final static int BARCODE = 6;
	final static String CARD_ACTION = "CARD_ACTION";
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.add_edit_card);
		final ImageView icon_view = (ImageView)findViewById(R.id.add_edit_card_icon);
		final Spinner icon = (Spinner)findViewById(R.id.add_edit_card_color);
		final TextView name = (TextView)findViewById(R.id.add_edit_card_name);
		final EditText name_editable = (EditText) findViewById(R.id.add_edit_card_name_editable);
		final EditText phone = (EditText)findViewById(R.id.add_edit_card_phone);
		final EditText balance = (EditText)findViewById(R.id.add_edit_card_balance);
		final EditText pin = (EditText)findViewById(R.id.add_edit_card_pin);
		final EditText note = (EditText)findViewById(R.id.add_edit_card_note);
		final EditText url = (EditText)findViewById(R.id.add_edit_card_url);
		final Button cancel = (Button)findViewById(R.id.add_edit_card_cancel_button);
		number = (EditText)findViewById(R.id.add_edit_card_num);
		save = (Button)findViewById(R.id.add_edit_card_save_button);
		expire = (TextView)findViewById(R.id.add_edit_card_expire);
		date_button = (Button)findViewById(R.id.add_edit_card_expire_button);
		mDb = new CardexDb(this).open();
		
		//SET FIELDS FOR A NEW CARD
		if(getIntent().getIntExtra(CARD_ACTION, -1) == ADD_CARD){
			mCard = new Card(getIntent().getStringExtra(CardexDb.CARD_NAME));
			mCard.phone = getIntent().getStringExtra(CardexDb.CARD_PHONE);
			mCard.icon = 0;
			if(mCard.phone.equals("")) mCard.phone = null;
			mCard.url = getIntent().getStringExtra(CardexDb.CARD_URL);
			if(mCard.url.equals("")) mCard.url = null;
			mCard.editable = getIntent().getIntExtra(CardexDb.CARD_EDITABLE, 1);
			if(savedInstanceState == null) showDialog(BARCODE_DIALOG);
			else mCard.format = savedInstanceState.getString("format");
			
		}
		else mCard = mDb.getCard(getIntent().getLongExtra(CardexDb.CARD_ID, -1));
		
		ArrayAdapter<CharSequence> icon_adapter = ArrayAdapter.createFromResource(
	            this, R.array.colors, android.R.layout.simple_spinner_item);
	    icon_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		icon.setAdapter(icon_adapter);
		icon.setSelection(mCard.icon);
		icon.setOnItemSelectedListener(new OnItemSelectedListener(){
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
				Card.setIcon(position, icon_view, mCard.name, mCard.editable);
				mCard.icon = position;
			}
			public void onNothingSelected(AdapterView<?> arg0) {
			}
		});
		
		name.setText(mCard.name);
		name_editable.setText(mCard.name);
		Card.setIcon(mCard.icon, icon_view, mCard.name, mCard.editable);
		if(mCard.balance != -1)
			balance.setText(my_format2.format(mCard.balance));
		if(mCard.barcode != null)
			number.setText(mCard.barcode);
		if(mCard.pin != null)
			pin.setText(mCard.pin);
		if(mCard.expire != null)
			updateDate();
		if(mCard.note != null)
			note.setText(mCard.note);
		if(mCard.phone != null)
			phone.setText(mCard.phone);
		if(mCard.url != null)
			url.setText(mCard.url);
		
		if(mCard.editable == 1){
			name.setVisibility(View.GONE);
			findViewById(R.id.add_edit_card_name_promt).setVisibility(View.VISIBLE);
			name_editable.setVisibility(View.VISIBLE);
		}
		
		
		OnClickListener mClickListener = new OnClickListener(){
			public void onClick(View v) {
				int id = v.getId();
				switch(id){
				case R.id.add_edit_card_save_button:
					String field = null;
					if(mCard.editable == 1){
						field = name_editable.getText().toString();
						if(field.equals("")){
							showDialog(MISSING_NAME_DIALOG);
							break;
						}
						else mCard.name = field;
					}
					
					field = phone.getText().toString();
					if(!field.equals("")) mCard.phone = field;
					else mCard.phone = null;
					
					field = balance.getText().toString();
					if(!field.equals("")) mCard.balance = Double.parseDouble(field);
					else mCard.balance = -1;
					
					field = number.getText().toString();
					if(!field.equals("")) mCard.barcode = field;
					else{ 
						mCard.barcode = null;
						mCard.format = null;
					}
					field = pin.getText().toString();
					if(!field.equals("")) mCard.pin = field;
					else mCard.pin = null;
					
					field = note.getText().toString();
					if(!field.equals("")) mCard.note = field;
					else mCard.note = null;
					
					field = url.getText().toString();
					if(!field.equals("")) mCard.url = field;
					else mCard.url = null;
					
					if(getIntent().getIntExtra(CARD_ACTION, -1) == ADD_CARD)
						mDb.addCard(mCard);
					else mDb.updateCard(mCard);
					finish();
					break;
					
				case R.id.add_edit_card_cancel_button:
					finish();
					break;
					
				case R.id.add_edit_card_expire_button:
					if(date_button.getText().equals(getResources().getString(R.string.set_expire)))
						showDialog(EXPIRE_DATE_DIALOG);
					else{
						date_button.setText(R.string.set_expire);
						expire.setText(R.string.no_expire);
						mCard.expire = null;
						
					}
					break;
				default:
					break;
				}
			}
		};
		date_button.setOnClickListener(mClickListener);
		save.setOnClickListener(mClickListener);
		cancel.setOnClickListener(mClickListener);
		
	}
	
	@Override
	public void onSaveInstanceState(Bundle outState){
		super.onSaveInstanceState(outState);
		outState.putString("format", mCard.format);
	}
	
	@Override
	public void onDestroy(){
		super.onDestroy();
		mDb.close();
	}

	@Override
	public Dialog onCreateDialog(int id){
		switch(id){
		case MISSING_NAME_DIALOG:
			return new AlertDialog.Builder(this).setMessage(R.string.no_name_dialog)
			.setPositiveButton(R.string.ok_button, new DialogInterface.OnClickListener(){
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
				}
			}).create();
			
		case EXPIRE_DATE_DIALOG:
			final Calendar mCal = Calendar.getInstance();
			return new DatePickerDialog(this, new OnDateSetListener(){

				public void onDateSet(DatePicker view, int year,
						int monthOfYear, int dayOfMonth) {
					mCal.set(year, monthOfYear, dayOfMonth);
					mCard.expire = mCal.getTime();
					updateDate();
					
				}}, 
				mCal.get(Calendar.YEAR), mCal.get(Calendar.MONTH), mCal.get(Calendar.DATE));
			
		case BARCODE_DIALOG:
			return new AlertDialog.Builder(this).setMessage(R.string.add_barcode_dialog)
			.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener(){
				public void onClick(DialogInterface dialog, int which) {
					IntentIntegrator.initiateScan(AddEditCard.this);
				}
			})
			.setNegativeButton(R.string.no, new DialogInterface.OnClickListener(){
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
				}
			}).create();
			
		default:
			return null;
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
	    menu.add(0, SAVE_CARD, 0, R.string.save_button).setIcon(android.R.drawable.ic_menu_save);
	    menu.add(0, BARCODE, 0, R.string.barcode_button).setIcon(android.R.drawable.ic_menu_camera);
	    menu.add(0, CANCEL, 0, R.string.cancel_button).setIcon(android.R.drawable.ic_menu_close_clear_cancel);
	    return true;
	}
	@Override
	// HANDLES MENU ITEM SELECTIONS
	public boolean onOptionsItemSelected(MenuItem item) {
	    switch (item.getItemId()) {
	    case SAVE_CARD:
	    	save.performClick();
	    	return true;
	    case CANCEL:
	    	finish();
	        return true;
	    case BARCODE:
	    	showDialog(BARCODE_DIALOG);
	    }
	    return false;
	}
	@Override
	protected void onActivityResult (int requestCode, int resultCode, Intent data) {
		switch(requestCode) {
		case IntentIntegrator.REQUEST_CODE:
			dismissDialog(BARCODE_DIALOG);
			if(resultCode == RESULT_OK){
				IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
				if (scanResult != null) {
					mCard.barcode=scanResult.getContents();
					number.setText(mCard.barcode);
					mCard.format=scanResult.getFormatName();
				}
			}
		}
	}
	
	private void updateDate(){
		date_button.setText(R.string.clear_expire);
		expire.setText(DateFormat.getDateInstance().format(mCard.expire));
	}
}
